package com.platform.component.excel.parser.impl;

import com.platform.comm.exceptions.RestApiException;
import com.platform.component.excel.parser.IExcelParser;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.compress.utils.Lists;
import org.apache.poi.ooxml.util.SAXHelper;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.xssf.eventusermodel.XSSFReader;
import org.apache.poi.xssf.model.SharedStringsTable;
import org.springframework.stereotype.Service;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;

import javax.xml.parsers.ParserConfigurationException;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.List;
import java.util.Objects;

/**
 * Excel解析
 *
 * @author libin
 */
@Service("excelparsertemp")
@Log4j2
public class ExcelParser implements IExcelParser {

    @Override
    public List<List<String>> readErrorExcel(File importFile) {
        List<List<String>> lists = Lists.newArrayList();
        try (InputStream inputStream = new FileInputStream(importFile);
             OPCPackage pkg = OPCPackage.open(inputStream)) {
            XSSFReader xssfReader = new XSSFReader(pkg);
            lists.addAll(processExcel(pkg, xssfReader));
        } catch (Exception e) {
            log.error("处理excel数据出现异常: {}", e.getMessage());
            throw new RestApiException(e.getMessage());
        }
        return lists;
    }

    @Override
    public List<List<String>> processExcel(OPCPackage pkg, XSSFReader xssfReader) throws Exception {
        if (log.isDebugEnabled()) {
            log.debug("start async process excel data.");
        }
        try (SharedStringsTable sst = xssfReader.getSharedStringsTable();
             InputStream dataSheet = xssfReader.getSheetsData().next()) {

            InputSource sheetSource = new InputSource(dataSheet);
            XMLReader parser = null;
            ExcelParseHandler handler = null;
            try {
                parser = SAXHelper.newXMLReader();
                handler = new ExcelParseHandler(sst);
                parser.setContentHandler(handler);
            } catch (SAXException | ParserConfigurationException e) {
                e.printStackTrace();
                log.error(e.getMessage(), e);
            }
            Objects.requireNonNull(parser).parse(sheetSource);
            return handler.getRetList();
        }
    }
}
